using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using NTTHAO.CommonWeb;
using NTTHAO.Common.BL;
using NTTHAO.Web.BL.CommonPage;
using System.IO;
using NTTHAO.Imaging;

public partial class admin_webparts_Plug_ins_CommonPage_CommonPageContentInput : System.Web.UI.UserControl
{
    public bool isAdmin = false;
    public CommonPageContent _Content = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        this.isAdmin = "admin".Equals(Context.User.Identity.Name, StringComparison.OrdinalIgnoreCase);
        this.chkRemoveImage.Text = this.chkRemoveMiniImage.Text = LanguageUtility.GetLanguageText("REMOVE", Session);
        this.btnSave2.Text = this.btnSave.Text = LanguageUtility.GetLanguageText("SAVE", Session);
        this.chkActive.Text = LanguageUtility.GetLanguageText("ACTIVE", Session);
        this.txtResizeImageWidth.Style[HtmlTextWriterStyle.TextAlign] = "right";
        this.txtResizeImageHeight.Style[HtmlTextWriterStyle.TextAlign] = "right";
        this.txtResizeMiniImageWidth.Style[HtmlTextWriterStyle.TextAlign] = "right";
        this.txtResizeMiniImageHeight.Style[HtmlTextWriterStyle.TextAlign] = "right";

        string adminCss = "../sites/" + NTTHAO.CommonWeb.WebGlobal.GetSite(Session).SiteID + "/Resources/css/default_admin.css";
        if (!System.IO.File.Exists(Server.MapPath(adminCss)))
        {
            adminCss = "../sites/" + NTTHAO.CommonWeb.WebGlobal.GetSite(Session).SiteID + "/Resources/css/default.css";
        }
        this._ContentCKEditor.ContentsCss = adminCss;
        this._ContentCKEditor.Entities = false;
        //this._ContentCKEditor.ForcePasteAsPlainText = true;

        if (!IsPostBack)
        {
            txtInsertDate.Text = DateTime.Now.ToString("dd/MM/yyyy");

            string action = Request.QueryString["action"];

            //this.chkResizeImage.Checked = false;
            this.txtResizeMiniImageWidth.Text = ConfigValues.GetConfigValue("CONTENT_MINI_IMAGE_WIDTH_RESIZE");
            this.txtResizeMiniImageHeight.Text = ConfigValues.GetConfigValue("CONTENT_MINI_IMAGE_HEIGHT_RESIZE");
            this.txtResizeImageWidth.Text = ConfigValues.GetConfigValue("CONTENT_IMAGE_WIDTH_RESIZE");
            this.txtResizeImageHeight.Text = ConfigValues.GetConfigValue("CONTENT_IMAGE_HEIGHT_RESIZE");

            //this.chkResizeImage.Checked = this.chkResizeMiniImage.Checked = false;

            for (int i = 0; i < 24; i++)
            {
                cmbInsertHour.Items.Add(new ListItem(i.ToString("00"), i.ToString("00")));
            }
            for (int i = 0; i < 60; i++)
            {
                cmbInsertMin.Items.Add(new ListItem(i.ToString("00"), i.ToString("00")));
            }
            this.cmbInsertHour.Text = DateTime.Now.Hour.ToString("00");
            this.cmbInsertMin.Text = DateTime.Now.Minute.ToString("00");

            if ("editcontent".Equals(action))
            {
                try
                {
                    int contentid = Int32.Parse(Request.QueryString["contentid"].Trim());
                    CommonPageContent content = new CommonPageContent(contentid);

                    if (content.ID < 1)
                    {
                        throw new Exception();
                    }
                    this._Content = content;

                    this.txtHeader.Text = content.Header;
                    this.txtDescription.Text = content.Description;
                    //this.txtContent.Text = content.Content;
                    this.txtViewType.Text = content.ViewType.ToString();
                    this.chkActive.Checked = content.Active;
                    this._ContentCKEditor.Text = content.Content;
                    this.txtInsertDate.Text = content.InsertDate.ToString("dd/MM/yyyy");
                    this.cmbInsertHour.Text = content.InsertDate.Hour.ToString("00");
                    this.cmbInsertMin.Text = content.InsertDate.Minute.ToString("00");
                }
                catch (Exception)
                {
                    Response.Redirect("CommonPageContent.aspx?action=invalidurl", false);
                    return;
                }
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            CommonPageContent content = null;
            string action = Request.QueryString["action"];

            if ("editcontent".Equals(action))
            {
                int contentid = Int32.Parse(Request.QueryString["contentid"].Trim());
                content = new CommonPageContent(contentid);

                if (this.isAdmin)
                {
                    content.ViewType = Int32.Parse(txtViewType.Text.Trim());
                }
            }
            else
            {
                int mnuid = Int32.Parse(Request.QueryString["mnuid"].Trim());
                if (mnuid < 1)
                {
                    throw new Exception();
                }
                content = new CommonPageContent();

                content.MenuID = mnuid;
                content.IsDefault = false;
                content.Reserve_01 = "";
                content.Image = "";
                content.MiniImage = "";
                content.ViewType = Int32.Parse(txtViewType.Text.Trim());
            }

            content.Header = txtHeader.Text.Trim();
            content.Description = txtDescription.Text.Trim();
            content.Content = _ContentCKEditor.Text.Trim();// txtContent.Text;
            content.Active = chkActive.Checked;
            try
            {
                string[] dSpl = txtInsertDate.Text.Trim().Split(new string[] { "/" }, StringSplitOptions.None);
                int hour = 0;
                int minute = 0;
                Int32.TryParse(cmbInsertHour.SelectedValue.Trim(), out hour);
                Int32.TryParse(cmbInsertMin.SelectedValue.Trim(), out minute);
                content.InsertDate = new DateTime(Convert.ToInt32(dSpl[2]), Convert.ToInt32(dSpl[1]), Convert.ToInt32(dSpl[0]), hour, minute, 0);
            }
            catch { }
            //content.InsertDate = new DateTime();

            string uploadedFileName = String.Empty;
            string miniFileName = String.Empty;
            string filePath = "../" + Constant.UPLOAD_FILE_PATH + "commonpage/";

            if (!System.IO.Directory.Exists(Server.MapPath(filePath)))
            {
                System.IO.Directory.CreateDirectory(Server.MapPath(filePath));
            }

            if (this.fuPresentativeImage.HasFile)
            {
                if (this.fuPresentativeImage.PostedFile.FileName.Contains("."))
                {
                    uploadedFileName = "Pre_" + DateTime.Now.Ticks.ToString() + this.fuPresentativeImage.PostedFile.FileName.Substring(this.fuPresentativeImage.PostedFile.FileName.LastIndexOf("."));

                    this.fuPresentativeImage.PostedFile.SaveAs(Server.MapPath(filePath + uploadedFileName));
                }
            }

            if (this.fuMiniImage.HasFile)
            {
                if (this.fuMiniImage.PostedFile.FileName.Contains("."))
                {
                    miniFileName = "Mini_" + DateTime.Now.Ticks.ToString() + this.fuMiniImage.PostedFile.FileName.Substring(this.fuMiniImage.PostedFile.FileName.LastIndexOf("."));

                    this.fuMiniImage.PostedFile.SaveAs(Server.MapPath(filePath + miniFileName));
                }
            }

            if ("editcontent".Equals(action, StringComparison.OrdinalIgnoreCase))
            {
                if (chkRemoveImage.Checked || uploadedFileName != string.Empty)
                {
                    if (System.IO.File.Exists(Server.MapPath(filePath + content.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath(filePath + content.Image));
                    }
                    if (System.IO.File.Exists(Server.MapPath(filePath + "Mini_" + content.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath(filePath + "Mini_" + content.Image));
                    }
                    content.Image = "";
                }

                if (miniFileName != string.Empty || chkRemoveMiniImage.Checked)
                {
                    if (System.IO.File.Exists(Server.MapPath(filePath + "/" + content.MiniImage)))
                    {
                        System.IO.File.Delete(Server.MapPath(filePath + "/" + content.MiniImage));
                    }
                    content.MiniImage = "";
                }
            }
            else
            {
                content.Image = content.MiniImage = "";
                content.Insert();
            }

            {
                try
                {
                    if (uploadedFileName != string.Empty)
                    {
                        content.Image = content.URLHeader + "-" + content.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + System.IO.Path.GetExtension(uploadedFileName);
                        string serverFilePath = Server.MapPath(filePath + content.Image);
                        if (File.Exists(serverFilePath))
                        {
                            File.Delete(serverFilePath);
                        }
                        File.Move(Server.MapPath(filePath + uploadedFileName), serverFilePath);

                        if (chkResizeImage.Checked || Constant.ADD_LAYER_MASK)
                        {
                            content.Image = System.IO.Path.GetFileName(ImageUtilities.CompressImageToJpeg(serverFilePath, ImageUtilities.HIGHT_PROGRESSIVE));
                            serverFilePath = Path.ChangeExtension(serverFilePath, Path.GetExtension(content.Image));
                        }

                        if (chkResizeImage.Checked)
                        {
                            int width = int.MaxValue, height = int.MaxValue;
                            width = Int32.TryParse(txtResizeImageWidth.Text.Trim(), out width) ? width : 10000;
                            height = Int32.TryParse(txtResizeImageHeight.Text.Trim(), out height) ? height : 10000;
                            if (width > 0 && height > 0)
                            {
                                string resizedImagePath = ImageUtilities.ResizeImageToJpeg(serverFilePath, width, height, ResizeOptions.MaximumSizeFix, System.Drawing.Color.White, ImageUtilities.HIGHT_PROGRESSIVE);
                                content.Image = Path.GetFileName(resizedImagePath);
                            }
                        }

                        //layer mask
                        if (Constant.ADD_LAYER_MASK)
                        {
                            float left = 0, top = 0, width = 0, height = 0, opacity = 1;
                            float.TryParse(ConfigValues.GetConfigValue("MASK_TOP_PERCENT").Trim(), out top);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_LEFT_PERCENT").Trim(), out left);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_WIDTH_PERCENT").Trim(), out width);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_HEIGHT_PERCENT").Trim(), out height);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_OPACITY").Trim(), out opacity);

                            ImageUtilities.DrawLayerMask(Path.ChangeExtension(serverFilePath, Path.GetExtension(content.Image)), Server.MapPath("../" + Constant.MASK_IMAGE_FILE), top, left, width, height, ResizeOptions.MaximumSizeFix, opacity, ImageUtilities.HIGHT_PROGRESSIVE);
                        }
                        // end
                    }
                }
                catch { }
                try
                {
                    if (miniFileName != string.Empty)
                    {
                        content.MiniImage = content.URLHeader + "-" + "Mini-" + content.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + System.IO.Path.GetExtension(miniFileName);
                        string serverFilePath = Server.MapPath(filePath + content.MiniImage);
                        if (File.Exists(serverFilePath))
                        {
                            File.Delete(serverFilePath);
                        }
                        File.Move(Server.MapPath(filePath + miniFileName), serverFilePath);

                        if (chkResizeMiniImage.Checked || Constant.ADD_LAYER_MASK)
                        {
                            serverFilePath = ImageUtilities.CompressImageToJpeg(serverFilePath, ImageUtilities.HIGHT_PROGRESSIVE);
                            content.MiniImage = System.IO.Path.GetFileName(serverFilePath);
                        }

                        if (chkResizeMiniImage.Checked)
                        {
                            int width = int.MaxValue, height = int.MaxValue;
                            width = Int32.TryParse(txtResizeMiniImageWidth.Text.Trim(), out width) ? width : 10000;
                            height = Int32.TryParse(txtResizeMiniImageHeight.Text.Trim(), out height) ? height : 10000;
                            if (width > 0 && height > 0)
                            {
                                string resizedImagePath = ImageUtilities.ResizeImageToJpeg(serverFilePath, width, height, ResizeOptions.MaximumSizeFix, System.Drawing.Color.White, ImageUtilities.HIGHT_PROGRESSIVE);
                                content.MiniImage = Path.GetFileName(resizedImagePath);
                            }
                        }

                        //layer mask
                        if (Constant.ADD_LAYER_MASK)
                        {
                            float left = 0, top = 0, width = 0, height = 0, opacity = 1;
                            float.TryParse(ConfigValues.GetConfigValue("MASK_TOP_PERCENT").Trim(), out top);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_LEFT_PERCENT").Trim(), out left);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_WIDTH_PERCENT").Trim(), out width);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_HEIGHT_PERCENT").Trim(), out height);
                            float.TryParse(ConfigValues.GetConfigValue("MASK_OPACITY").Trim(), out opacity);

                            ImageUtilities.DrawLayerMask(Path.ChangeExtension(serverFilePath, Path.GetExtension(content.MiniImage)), Server.MapPath("../" + Constant.MASK_IMAGE_FILE), top, left, width, height, ResizeOptions.MaximumSizeFix, opacity, ImageUtilities.HIGHT_PROGRESSIVE);
                        }
                        // end
                    }
                }
                catch { }

                content.Update();
            }

            /*
            if ("editcontent".Equals(action))
            {
                if (chkRemoveImage.Checked || uploadedFileName != string.Empty)
                {
                    if (content.Image != null && content.Image.Trim().Length > 0 && System.IO.File.Exists(Server.MapPath(filePath + content.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath(filePath + content.Image.Trim()));
                    }
                    content.Image = "";
                }
                if (uploadedFileName != string.Empty)
                {
                    content.Image = "Content_" + content.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + uploadedFileName.Substring(uploadedFileName.LastIndexOf("."));
                    if (System.IO.File.Exists(Server.MapPath(filePath + content.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath(filePath + content.Image));
                    }
                    System.IO.File.Move(Server.MapPath(filePath + uploadedFileName), Server.MapPath(filePath + content.Image));
                }
                if (chkRemoveMiniImage.Checked || miniFileName != string.Empty)
                {
                    if (content.MiniImage != null && content.MiniImage.Trim().Length > 0 && System.IO.File.Exists(Server.MapPath(filePath + content.MiniImage)))
                    {
                        System.IO.File.Delete(Server.MapPath(filePath + content.MiniImage.Trim()));
                    }
                    content.MiniImage = "";
                }
                if (miniFileName != string.Empty)
                {
                    content.MiniImage = "Content_Mini_" + content.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + miniFileName.Substring(miniFileName.LastIndexOf("."));
                    if (System.IO.File.Exists(Server.MapPath(filePath + content.MiniImage)))
                    {
                        System.IO.File.Delete(Server.MapPath(filePath + content.MiniImage));
                    }
                    System.IO.File.Move(Server.MapPath(filePath + miniFileName), Server.MapPath(filePath + content.MiniImage));
                }

                content.Update();
            }
            else
            {
                content.Image = "";
                content.MiniImage = "";
                content.Insert();

                if (!System.IO.Directory.Exists(Server.MapPath(filePath)))
                {
                    System.IO.Directory.CreateDirectory(Server.MapPath(filePath));
                }
                if (uploadedFileName != string.Empty)
                {
                    content.Image = "Content_" + content.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + uploadedFileName.Substring(uploadedFileName.LastIndexOf("."));
                    if (System.IO.File.Exists(Server.MapPath(filePath + content.Image)))
                    {
                        System.IO.File.Delete(Server.MapPath(filePath + content.Image));
                    }
                    System.IO.File.Move(Server.MapPath(filePath + uploadedFileName), Server.MapPath(filePath + content.Image));
                }

                if (miniFileName != string.Empty)
                {
                    content.MiniImage = "Content_Mini_" + content.ID.ToString() + "_" + DateTime.Now.Ticks.ToString() + miniFileName.Substring(miniFileName.LastIndexOf("."));
                    if (System.IO.File.Exists(Server.MapPath(filePath + content.MiniImage)))
                    {
                        System.IO.File.Delete(Server.MapPath(filePath + content.MiniImage));
                    }
                    System.IO.File.Move(Server.MapPath(filePath + miniFileName), Server.MapPath(filePath + content.MiniImage));
                }

                if (uploadedFileName != string.Empty || miniFileName != string.Empty)
                {
                    content.Update();
                }
            }
            */
            Response.Redirect("CommonPageContent.aspx?action=view&g=" + Request.QueryString["g"] + "&mnuid=" + Request.QueryString["mnuid"] + "&time=" + DateTime.Now.Ticks.ToString(), false);
        }
        catch (Exception)
        {
        }
    }
}
